package com.sunday.pinxinghui.model;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.adapter.CommonAdapter;
import com.sunday.pinxinghui.adapter.ViewHolder;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.base.Constant;
import com.sunday.pinxinghui.entity.Message;
import com.sunday.pinxinghui.network.ApiClient;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Author by Damon,  on 2017/12/4.
 */

public class MessageListActivity extends BaseActivity {


    @Bind(R.id.left_btn)
    ImageView leftBtn;
    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.rightTxt)
    TextView rightTxt;
    @Bind(R.id.right_btn)
    ImageView rightBtn;
    @Bind(R.id.common_header)
    RelativeLayout commonHeader;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    private CommonAdapter<Message> adapter;
    private List<Message> dataSet = new ArrayList<>();
    private int pageNo = 1;
    private boolean isCanLoadMore;
    private int lastVisibleItem;
    private LinearLayoutManager layoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_list);
        ButterKnife.bind(this);
        titleView.setText("消息盒子");
        initRecyclerView();
        getData();

    }

    private void initRecyclerView() {
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setPadding(20, 20, 20, 0);
        adapter = new CommonAdapter<Message>(mContext, R.layout.list_item_message, dataSet) {
            @Override
            public void convert(ViewHolder holder, Message message, int position) {
                bind(holder, message);
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .margin(20)
                .build());
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanLoadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });


        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageNo=1;
                getData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });

        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo=1;
                getData();
            }
        });

    }


    private void getData() {
        Call<ResultDO<List<Message>>> call = ApiClient.getApiAdapter().getMessageList(BaseApplication.getInstance().getMember().getId(),
                1, 1, pageNo, Constants.PAGE_SIZE);
        call.enqueue(new Callback<ResultDO<List<Message>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Message>>> call, Response<ResultDO<List<Message>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                ptrFrame.refreshComplete();
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    dataSet.addAll(response.body().getResult());
                    adapter.notifyDataSetChanged();
                    if (response.body().getResult().size() == Constants.PAGE_SIZE) {
                        pageNo++;
                        isCanLoadMore = true;
                    } else {
                        isCanLoadMore = false;
                    }
                    if (dataSet.size() > 0) {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Message>>> call, Throwable t) {
                ptrFrame.refreshComplete();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });

    }

    private void bind(ViewHolder holder, Message message) {
       ((TextView) (holder.getView(R.id.message_title))).setText("消息");
        ((TextView) (holder.getView(R.id.message_time))).setText(message.getTime());
        ((TextView) (holder.getView(R.id.message_content))).setText(message.getMessage());
    }

}
